package com.java.comprehensive.arithmetic.leecode.easy;

/**
 * @program: comprehensive-service
 * @description: 长度最小的数组
 * @author: 窦绍飞
 * @create: 2022-01-12 18:12
 **/
public class LeetCode_209 {

    public static int minSubArrayLen(int target, int[] nums) {
        int result = 0;
        if (nums.length < 1) {
            return result;
        }
        int n = nums.length;
        int ans = Integer.MAX_VALUE;
        int start = 0, end = 0;
        int sum = 0;
        while (end < n) {
            sum += nums[end];
            while (sum >= target) {
                ans = Math.min(ans, end - start + 1);
                sum -= nums[start];
                start++;
            }
            end++;
        }
        int num = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i > target - 1) {
                num = num - nums[i - target] + nums[i];
                result = Math.min(result, num);
            } else {
                num = num + nums[i];
                result = num;
            }
        }
        return result;
    }

    public static Integer slidingWindow(int[] nums, int target) {
        int result = Integer.MAX_VALUE;
        int i = 0;
        int sum = 0;
        for (int j = 0; j < nums.length; j++) {
            sum += nums[j];
            while (sum >= target) {
                int subl = j - i + 1;
                result = Math.min(result, subl);
                sum -= nums[i];
                i++;
            }
        }
        return result == Integer.MAX_VALUE ? 0 : result;
    }

    public static void main(String[] args) {
        int nums[] = {2, 3, 1, 2, 4, 3};
        int i = minSubArrayLen(7, nums);
        System.out.println(i);
    }
}
